package br.ufc.ck0017.compiler;

import br.ufc.ck0017.parser.MiniJavaParser;
import br.ufc.ck0017.parser.ParseException;
import br.ufc.ck0017.syntaxtree.Program;
import br.ufc.ck0017.visitor.typechecking.SymbolTableVisitor;
import br.ufc.ck0017.visitor.typechecking.TypeCheckVisitor;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class Compiler {
    public static void main(String[] args) {
        try {
            String filePath = args[0];
            FileInputStream fileInputStream = new FileInputStream(new File(filePath));

            System.out.println("Parsing MiniJava code: " + filePath);
            Program root = new MiniJavaParser(fileInputStream).Goal();
            System.out.println("File parsed with success.");

            System.out.println("Running SymbolTableVisitor...");
            SymbolTableVisitor symbolTableVisitor = new SymbolTableVisitor();
            root.accept(symbolTableVisitor);

            if (symbolTableVisitor.getErrorMessages().isEmpty()) {
                System.out.println("SymbolTableVisitor executed with success. No errors found.");
            } else {
                System.out.println("Compilation error: ");

                for (String errorMessage : symbolTableVisitor.getErrorMessages()) {
                    System.out.println(errorMessage);
                }

                return;
            }

            System.out.println("Running TypeCheckVisitor...");
            TypeCheckVisitor typeCheckVisitor = new TypeCheckVisitor(symbolTableVisitor.getProgram());
            root.accept(typeCheckVisitor);

            if (typeCheckVisitor.getErrorMessages().isEmpty()) {
                System.out.println("SymbolTableVisitor executed with success. No errors found.");
            } else {
                System.out.println("Compilation error: ");

                for (String errorMessage : symbolTableVisitor.getErrorMessages()) {
                    System.out.println(errorMessage);
                }

                return;
            }

            System.out.println("Translation to intermediate representation not fully implemented. Skip.");
            System.out.println("Canonical representation not fully implemented. Skip.");
            System.out.println("Instruction selection not fully implemented. Skip.");
            System.out.println("Liveness analysis not fully implemented. Skip.");
            System.out.println("Register allocation not fully implemented. Skip.");
        } catch (FileNotFoundException | ParseException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}
